<template>
  <div>
    <table class="table table-sm table-bordered approve-table">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td>{{ approveData.label }}</td>
          <td colspan="3" class="text-left p-0 report-input-td">
            <div v-for="(r, index) of record" :key="index" class="d-flex p-item">
              <div style="width: 20%" class="p-label">{{ r.approval_person }}</div>
              <div class="flex-1">
                <div v-if="r.editable && !isView" style="background-color: #ffffee" class="p-2">
                  <c-radio-group
                    :options="enumCommitteeType"
                    v-model="approveForm.approval_status"
                    number-key
                  ></c-radio-group>
                  <div
                    v-if="![0, 1].includes(approveForm.approval_status)"
                    class="border rounded mt-2 w-100"
                  >
                    <el-input
                      v-model="approveForm.approval_option"
                      placeholder="请填写意见"
                    ></el-input>
                  </div>
                  <div class="p-2 d-flex justify-content-between">
                    <div>签字：{{ approveForm.approval_person }}</div>
                    <div class="w-50">日期：{{ approveForm.dateStr }}</div>
                  </div>
                </div>
                <record-item v-else :record-data="r"></record-item>
              </div>
            </div>
            <div class="d-flex p-item">
              <div style="width: 20%" class="p-label">结果</div>
              <div class="p-2">
                参会委员人数{{ approvalResult.total }}人; 有效投票人{{
                  approvalResult.validTotal
                }}人。
                <div>
                  同意票{{ approvalResult.agreeTotal }}张；否决票{{
                    approvalResult.vetoTotal
                  }}张；复议票{{ approvalResult.resTotal }}张；有条件同意票{{
                    approvalResult.conditionTotal
                  }}张。
                </div>
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>

    <div class="text-center my-3" v-if="!isAllView">
      <el-button class="btn-long" type="primary" :loading="loading" @click="handlePass">
        确定
      </el-button>
      <el-button class="btn-long" :disabled="loading" @click="handleDismiss">取消</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { addApprove, updateApprove } from '@/credit/mixin/wf'
import { enumCommitteeType } from '@/credit/views/county/unionProvince/components/projectApprove/index'

export default {
  components: {
    'record-item': {
      functional: true,
      props: {
        recordData: {
          type: Object,
          default: () => ({}),
        },
      },
      render: (h, ctx) => {
        const { recordData } = ctx.props
        const label = enumCommitteeType[recordData.approval_status] || ''
        const hasOpinion = recordData.approval_status !== 1
        return recordData.approval_status === 0
          ? h('div', { class: 'p-2 text-muted' }, '-')
          : h('div', { class: 'p-2' }, [
              h(
                'div',
                { class: 'text-left' },
                label + (hasOpinion ? ': ' + recordData.approval_option || '-' : '')
              ),
              h('div', { class: 'd-flex justify-content-between' }, [
                h('span', `签字：${recordData.approval_person || ''}`),
                h('span', `日期：${recordData.dateStr}`),
              ]),
            ])
      },
    },
  },
  props: {
    relatedData: {
      type: Object,
      default: () => ({}),
    },
    approveData: {
      type: Object,
      default: () => ({
        editable: false,
        record: [],
      }),
    },
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      enumCommitteeType,
      loading: false,
      approveForm: {
        approval_option: '',
        approval_person: '',
        dateStr: '',
        id: '',
        task_id: '',
        approval_status: 0,
      },
    }
  },
  computed: {
    ...mapGetters(['userId', 'user']),
    relatedId() {
      return this.relatedData.customer_related_id
    },
    record() {
      return this.approveData.record
    },
    isView() {
      return this.viewMode || !this.approveData.editable
    },
    isAllView() {
      return this.isView || this.record.every(it => !it.editable)
    },
    approvalResult() {
      const { record } = this
      let agreeTotal = 0
      let vetoTotal = 0
      let resTotal = 0
      let conditionTotal = 0
      let validTotal = 0
      record.forEach(item => {
        if (item.approval_status) {
          validTotal++
        }
        if (item.approval_status === 1) {
          agreeTotal++
        } else if (item.approval_status === 2) {
          vetoTotal++
        } else if (item.approval_status === 3) {
          resTotal++
        } else if (item.approval_status === 4) {
          conditionTotal++
        }
      })
      return {
        total: record.length,
        validTotal,
        agreeTotal,
        vetoTotal,
        resTotal,
        conditionTotal,
      }
    },
  },
  watch: {
    record: {
      handler: function () {
        this.init()
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    init() {
      if (this.isAllView) return
      const item = this.record.find(it => it.editable)
      if (!item) return
      Object.keys(this.approveForm).forEach(key => {
        this.approveForm[key] = item[key] || ''
      })
      if (!this.approveForm.approval_status) {
        this.approveForm.approval_status = 0
      }
    },

    validateOpinion() {
      const { approval_status: status, approval_option: opinion } = this.approveForm
      if (status === 0) {
        return '请选择审批结果'
      }
      if (status !== 1 && !opinion) {
        return '请输入审批意见'
      }
      return ''
    },

    async handlePass() {
      const msg = this.validateOpinion()
      if (msg) {
        return this.$message.warning(msg)
      }

      this.loading = true
      return this.addApproveData()
        .then(res => {
          this.$message.success('操作成功！')
          this.$emit('success', res)
        })
        .catch(err => {
          this.$message.error('操作失败，请重试！')
          throw new Error(err)
        })
        .finally(() => {
          this.loading = false
        })
    },

    handleDismiss() {
      this.$emit('dismiss')
    },

    addApproveData() {
      const { approval_option: opinion, approval_status: status } = this.approveForm
      const { process } = this.approveData
      const { id, task_id: taskId } = this.record.find(it => it.editable) || {}

      const data = {
        opinion,
        status,
        process,
        taskId,
      }

      return id ? updateApprove(id, data, this.user) : addApprove(this.relatedId, data, this.user)
    },
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';

.p-label {
  padding: 0.5rem;
  border-right: 1px solid $border-color;
}
</style>
